package com.jinrustar.shenjiyingcommon.common.util;

import java.util.Map;
import java.util.TreeMap;

public class SignUtil {


    /**
     * 对 key:value 中 key 按ascii码值顺序排序
     *
     * @param parametersMap
     * @return
     */
    public static Map sortedToMap(Map<String, Object> parametersMap) {
        Map<String, Object> sortedMap = new TreeMap<>();
        for (String k : parametersMap.keySet()) {
            sortedMap.put(k, parametersMap.get(k));
        }
        return sortedMap;
    }

    /**
     * 使用&连接map中的key=value api签名需要
     *
     * @param paramsMap
     * @param apiKey
     * @return
     */
    public static String concatWithApiKey(Map<String, Object> paramsMap, String apiKey) {
        String str = "";
        str += concatWithoutKey(paramsMap);
        str += "key=" + apiKey;
        return str;
    }


    public static String concatWithoutKey(Map<String, Object> paramsMap) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : paramsMap.keySet()) {
            stringBuilder.append(key).append("=").append(paramsMap.get(key)).append("&");
        }
        return stringBuilder.toString();
    }

    public static String getMd5Str(String str) {
        String md5Str = Md5Util.encrypt(str.getBytes());
        if (md5Str == null) return null;
        return md5Str.toUpperCase();/*DigestUtils.md5Hex(str.getBytes()).toUpperCase();*/
    }


}
